package org.example.kafka.test;

import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.common.serialization.StringDeserializer;
import org.apache.kafka.common.serialization.StringSerializer;

import java.util.Collections;
import java.util.HashMap;

public class Consumer {

    //消费者代码
    public static void main(String[] args) {
        // todo 配置属性集合
        HashMap<String, Object> configMap = new HashMap<String,Object>();
        // TODO 配置属性：Kafka集群地址
        //configMap.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG,"localhost:9092");
        configMap.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092");
        // TODO 配置属性: Kafka传输的数据为KV对，所以需要对获取的数据分别进行反序列化
        configMap.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
        configMap.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG,StringDeserializer.class.getName());
        configMap.put(ConsumerConfig.GROUP_ID_CONFIG,"atguigu");
        // todo 创建消费者对象
        //KafkaConsumer<String, String> kafkaConsumer = new KafkaConsumer<>(configMap);
        KafkaConsumer<String,String> consumer = new KafkaConsumer<String,String>(configMap);
        // 消费者订阅主题数据
        consumer.subscribe(Collections.singletonList("test"));
        while (true){
            // 消费者从kafka中拉取数据
            ConsumerRecords<String, String> datas = consumer.poll(100);
            for (ConsumerRecord<String, String> data : datas) {
                System.out.println("K = " + data.key() + ", V = " + data.value());
            }
        }
        //关闭资源
        // kafkaConsumer.close();
    }
}
